//
//  WLRouterShareDiskController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/18.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRouterShareDiskController.h"
//#import "WLDiskChartView.h"
#import "WLWebViewController.h"
#import "NSString+Ext.h"

@interface WLRouterShareDiskController ()<UITextFieldDelegate>//,RouterSocketDelegate>

@property (nonatomic, strong) UIView *chartView;
@property (nonatomic, strong) UILabel *labTotal;
@property (nonatomic, strong) UILabel *labShare;
@property (nonatomic, assign) NSInteger totalSize;
@property (nonatomic, assign) NSInteger shareSize;
@property (nonatomic, strong) UITextField *textNum;

@end

@implementation WLRouterShareDiskController

- (void)dealloc
{
//    [[WLSocketManager sharedSocketManager] removeDelegate:self];
    [[WLSocketManager sharedSocketManager] removeDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"共享磁盘管理";
    
    _chartView = [[UIView alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-WLScaleX(170))/2.0, WLScaleX(40), WLScaleX(170), WLScaleX(170))];
    [self.view addSubview:_chartView];
//    [self showChartView];
    _labTotal = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(_chartView.frame)+WLScaleX(45), CGRectGetMinY(_chartView.frame)+(_chartView.frame.size.height-WLScaleX(50))/2.0, _chartView.frame.size.width-WLScaleX(70), WLScaleX(25))];
    _labTotal.font = [WLCommonTool fontTypePingFangSCMedium:14];
    _labTotal.textColor = wlDarkGrayColor;
//    _labTotal.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_labTotal];
    
    _labShare = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(_chartView.frame)+WLScaleX(45), CGRectGetMaxY(_labTotal.frame), _chartView.frame.size.width-WLScaleX(70), WLScaleX(25))];
    _labShare.font = [WLCommonTool fontTypePingFangSCMedium:14];
    _labShare.textColor = wlDarkGrayColor;
//    _labShare.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_labShare];
    
    UIView *shareView = [[UIView alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-WLScaleX(180))/2.0, CGRectGetMaxY(_chartView.frame)+WLScaleX(30), WLScaleX(180), WLScaleX(30))];
    shareView.layer.cornerRadius = 5;
    shareView.layer.masksToBounds = YES;
    shareView.layer.borderWidth = 1;
    shareView.layer.borderColor = wlUIColorRGB(0x29A8FA).CGColor;
    [self.view addSubview:shareView];
    
    UIButton *btnLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, WLScaleX(44), WLScaleX(30))];
    [btnLeft setImage:[UIImage imageNamed:@"minus_sign"] forState:UIControlStateNormal];
    [btnLeft addTarget:self action:@selector(minusStorageAction) forControlEvents:UIControlEventTouchUpInside];
    [shareView addSubview:btnLeft];
    
    UIView *lineLeft = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(44), 0, 1, WLScaleX(30))];
    lineLeft.backgroundColor = wlUIColorRGB(0x29A8FA);
    [shareView addSubview:lineLeft];
    
    _textNum = [[UITextField alloc] initWithFrame:CGRectMake(WLScaleX(44)+1, 0, WLScaleX(90), WLScaleX(30))];
    _textNum.delegate = self;
    _textNum.keyboardType = UIKeyboardTypeNumberPad;
    _textNum.textAlignment = NSTextAlignmentCenter;
    _textNum.font = [WLCommonTool fontTypePingFangSCMedium:14];
    _textNum.textColor = wlBlackColor;
    [shareView addSubview:_textNum];
    UILabel *labLeft = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 15, WLScaleX(30))];
    labLeft.backgroundColor = [UIColor clearColor];
    labLeft.font = [WLCommonTool fontTypePingFangSCMedium:14];
    labLeft.textColor = wlBlackColor;
    labLeft.text = @"G";
    _textNum.rightView = labLeft;
    _textNum.rightViewMode = UITextFieldViewModeAlways;
    
    UIView *lineRight = [[UIView alloc] initWithFrame:CGRectMake(WLScaleX(180-44)-1, 0, 1, WLScaleX(30))];
    lineRight.backgroundColor = wlUIColorRGB(0x29A8FA);
    [shareView addSubview:lineRight];
    
    UIButton *btnRight = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(180-44), 0, WLScaleX(44), WLScaleX(30))];
    [btnRight setImage:[UIImage imageNamed:@"add_sign"] forState:UIControlStateNormal];
    [btnRight addTarget:self action:@selector(addStorageAction) forControlEvents:UIControlEventTouchUpInside];
    [shareView addSubview:btnRight];
    
//    UILabel *labTip = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMaxY(shareView.frame)+WLScaleX(10), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(20))];
    UILabel *labTip = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-(14+4+200))/2.0+18, CGRectGetMaxY(shareView.frame)+WLScaleX(10), 200, WLScaleX(20))];
    labTip.backgroundColor = [UIColor clearColor];
    labTip.font = [WLCommonTool fontTypePingFangSCRegular:12];
    labTip.textColor = wlLightTextColor;
//    labTip.textAlignment = NSTextAlignmentCenter;
    labTip.text = @"共享空间设置为0,表示关闭共享磁盘.";
    [self.view addSubview:labTip];
    
    UIImageView *ivTip = [[UIImageView alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-(14+4+200))/2.0, CGRectGetMidY(labTip.frame)-7, 14, 14)];
    ivTip.image = [UIImage imageNamed:@"disk_tip"];
    [self.view addSubview:ivTip];
    
    UIButton *btnSave = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(16), CGRectGetMaxY(shareView.frame)+WLScaleX(40), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(47))];
    CAGradientLayer *gradientBtn = [CAGradientLayer layer];
    gradientBtn.frame = btnSave.bounds;  // 设置显示的frame
    gradientBtn.colors = @[(__bridge id)wlUIColorRGB(0x1A59E2).CGColor,(__bridge id)wlUIColorRGB(0x2292F5).CGColor]; // 设置渐变颜色
    gradientBtn.startPoint = CGPointMake(0, 0);
    gradientBtn.endPoint = CGPointMake(1, 0);
    [btnSave.layer insertSublayer:gradientBtn atIndex:0];
    
    btnSave.layer.cornerRadius = 5;//WLScaleX(5);
    btnSave.layer.masksToBounds = YES;
    btnSave.titleLabel.font = [WLCommonTool fontTypePingFangSCMedium:16];
    [btnSave setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnSave setTitle:@"保存设置" forState:UIControlStateNormal];
    [btnSave addTarget:self action:@selector(saveStorageAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSave];
    
    UILabel *labHelp = [[UILabel alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-110)/2.0, CGRectGetMaxY(btnSave.frame)+5, 110, 30)];
    labHelp.textAlignment = NSTextAlignmentCenter;
    labHelp.font = [WLCommonTool fontTypePingFangSCRegular:12];
    labHelp.textColor = wlLightTextColor;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"《磁盘设置帮助》"];// attributes:@{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]}];
    [attrStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(1, 6)];
    labHelp.attributedText = attrStr;
    [self.view addSubview:labHelp];
    UIButton *btnHelp = [[UIButton alloc] initWithFrame:CGRectMake((WIDTH_SCREEN_WL-110)/2.0, CGRectGetMaxY(btnSave.frame)+5, 110, 30)];
//    [btnHelp setTitle:@"《磁盘设置帮助》" forState:UIControlStateNormal];
    [btnHelp addTarget:self action:@selector(diskHelpAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnHelp];
    
    [[WLSocketManager sharedSocketManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
    [self receiveRouterDiskGet];
    
//    [self getRouterStorage];
}

- (void)showChartViewShareStorage//:(NSInteger)shareSize
{
    [_chartView.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    
    CGPoint center = CGPointMake(_chartView.frame.size.width / 2.f, _chartView.frame.size.height / 2.f);
    CGFloat radius = _chartView.frame.size.height / 2.f-WLScaleX(10);
    if (_shareSize>=_totalSize) {
        UIBezierPath *arcPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:-M_PI_2 endAngle:M_PI*2 clockwise:YES];
        
        CAShapeLayer* shapelayer = [CAShapeLayer layer];
        shapelayer.lineWidth = WLScaleX(20);
        shapelayer.strokeColor = wlblueColor.CGColor;
        shapelayer.fillColor = [UIColor clearColor].CGColor;
        shapelayer.path = arcPath.CGPath;
        [_chartView.layer addSublayer:shapelayer];
        return;
    }
    float strart = (M_PI * 270)/ 180.0;
    float du = (_shareSize/(_totalSize*1.0))*360+270.0;
    float hudu = (M_PI*(du > 360 ? (du - 360) : du))/180.0;
    
    UIBezierPath *Path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:strart endAngle:hudu clockwise:YES];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = Path.CGPath;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.strokeColor = wlblueColor.CGColor;
    layer.lineWidth = WLScaleX(20);
    [_chartView.layer addSublayer:layer];
    /*
     CAGradientLayer* gradientLayer = [CAGradientLayer layer];
     gradientLayer.frame = chartView.bounds;
     gradientLayer.backgroundColor = [UIColor blueColor].CGColor;
     [chartView.layer addSublayer:gradientLayer];
     
     CAGradientLayer* firstLayer = [CAGradientLayer layer];
     firstLayer.frame = CGRectMake(0, 0, chartView.frame.size.width * 0.5, chartView.frame.size.height);
     firstLayer.colors = @[(id)wlUIColorRGB(0x2292F5).CGColor,(id)wlblueColor.CGColor];
     firstLayer.locations = @[@0.1,@1.0];
     firstLayer.startPoint = CGPointMake(0, 0);
     firstLayer.endPoint = CGPointMake(1, 0);
     [gradientLayer addSublayer:firstLayer];
     
     CAShapeLayer* gressLayer = [CAShapeLayer layer];
     gressLayer.lineWidth = 10.0;
     gressLayer.strokeColor = [UIColor blueColor].CGColor;
     gressLayer.fillColor = [UIColor clearColor].CGColor;
     gressLayer.lineCap = @"round";
     gressLayer.path = Path.CGPath;
     gradientLayer.mask = gressLayer;
     */
    float space = (_shareSize>0&&_shareSize<_totalSize)?0.05:0;
    float move = (M_PI*((_totalSize-_shareSize)/(_totalSize*1.0))*360)/180.0-space+hudu;
    float stat = hudu+space;
    UIBezierPath *pathTwo = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:stat endAngle:move clockwise:YES];
    CAShapeLayer *layerTwo = [CAShapeLayer layer];
    layerTwo.path = pathTwo.CGPath;
    layerTwo.fillColor = [UIColor clearColor].CGColor;
    layerTwo.strokeColor = wlUIColorRGB(0x2292F5).CGColor;
    layerTwo.lineWidth = WLScaleX(16);
    [_chartView.layer addSublayer:layerTwo];
    
}

- (void)getRouterStorage
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/app/getmemory" withParamsDic:nil success:^(NSDictionary *successDict) {
        [weakSelf showStorage:successDict[@"object"]];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)showStorage:(NSDictionary *)dict
{
    _totalSize = [dict[@"total"] integerValue];
    _shareSize = [dict[@"share"] integerValue];
//    if (_totalSize>0)
//    {
    unsigned long long shareSize = [dict[@"share"] unsignedLongLongValue];
    
    unsigned long long totalSize = [dict[@"total"] unsignedLongLongValue];
    _labTotal.text = [NSString stringWithFormat:@"总计：%lluG", totalSize/ MB_UNIT];
        NSString *strShare = [NSString stringWithFormat:@"%llu",shareSize / MB_UNIT];
        _labShare.text = [NSString stringWithFormat:@"共享：%@G",strShare];
        _textNum.text = strShare;
        [self showChartViewShareStorage];
//    }
}

- (void)minusStorageAction
{
    [_textNum resignFirstResponder];
    if (_shareSize<=16*MB_UNIT) {
        _shareSize = 0;
    } else {
        _shareSize -= MB_UNIT;
    }
    [self updateShow];
}

- (void)addStorageAction
{
    [_textNum resignFirstResponder];
    int shareGB = (int)_shareSize / MB_UNIT;
    int totalGB = (int)_totalSize / MB_UNIT;
    if (shareGB >= totalGB) {
        [self showHUDMessage:@"已达到磁盘空间最大值"];
        return;
    }
    if (shareGB < 16) {
        _shareSize = 16 * MB_UNIT;
    } else {
        _shareSize += MB_UNIT;
    }
    if (shareGB > totalGB) {
        _shareSize = totalGB * MB_UNIT;
    }
    [self updateShow];
}

- (void)updateShow
{
//    _labTotal.text = [NSString stringWithFormat:@"总计：%ldG",_totalSize-_shareSize];
    int shareGB = (int)_shareSize/(1024*1024.0);
    NSString *strShare = [NSString stringWithFormat:@"%d", shareGB];
    _labShare.text = [NSString stringWithFormat:@"共享：%@G",strShare];;
    _textNum.text = strShare;
    [self showChartViewShareStorage];
}

- (void)saveStorageAction
{
    BOOL isShow = NO;
    if (_textNum.isEditing||_textNum.isFirstResponder) {
        isShow = YES;
    }
    [_textNum resignFirstResponder];
    if (_shareSize>0&&_shareSize<16*MB_UNIT)
    {
        [self showHUDMessage:@"设置空间小于16G,请重新设置"];
        return;
    }
    if (_textNum.text.integerValue > _totalSize / MB_UNIT) {
        [self showHUDMessage:@"共享空间应小于总空间,请重新设置"];
        return;
    }
    NSDictionary *dictParamer = @{@"total":@(_totalSize),@"share":@(_shareSize)};
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParamer options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *strContent = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *dict = @{@"type":@"DEVICE_DISK_SET",@"content":strContent};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
    
//    WLWkSelf
//    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/app/setmemory" withParamsDic:dict success:^(NSDictionary *successDict) {
//        [weakSelf showHUDMessage:successDict[@"message"]];
//    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
//    } error:^(NSError *error) {
//
//    } inView:self.view];
}

- (void)receiveRouterDiskSet
{
    NSDictionary *dict = @{@"type":@"DEVICE_DISK_SET",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)receiveRouterDiskGet
{
    NSDictionary *dict = @{@"type":@"DEVICE_DISKGET_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
    if ([msgModel.type isEqualToString:@"DEVICE_DISKGET_REP"])
    {
        if (msgModel.content != nil) {
            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            [self showStorage:dic];
        }
    }
    else if ([msgModel.type isEqualToString:@"COMMON_SUCCESS"])
    {
        [self showHUDMessage:@"设置成功"];
    }
}

- (void)diskHelpAction
{
    WLWebViewController *webView = [[WLWebViewController alloc] init];
//    webView.urlStr = @"http://47.75.195.106/help/helpdetail.html?detail=15";
    webView.urlStr = [NSString stringWithFormat:@"%@/help/helpdetail.html?detail=15",[WLCommonTool getWebHost]];
    webView.titleStr = @"磁盘设置帮助";
    [self.navigationController pushViewController:webView animated:YES];
}

#pragma mark - UITextField
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    NSString *strText = [_textNum.text stringByReplacingOccurrencesOfString:@"G" withString:@""];
//    _textNum.text = strText;
//    return YES;
//}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
//    NSString *strSize = [textField.text stringByReplacingOccurrencesOfString:@"G" withString:@""];
//    _shareSize = textField.text.integerValue;
    _shareSize = (NSInteger)((textField.text.floatValue)*MB_UNIT);
    [self updateShow];
//    if ([_textNum.text hasSuffix:@"G"]==NO) {
//        NSString *strText = [_textNum.text stringByAppendingString:@"G"];
//        _textNum.text = strText;
//    }
    if (_shareSize>0&&_shareSize<16*MB_UNIT)
    {
        [self showHUDMessage:@"设置空间小于16G,请重新设置"];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) {
        return YES;
    }
    NSString *strSize = [textField.text stringByAppendingString:string];
//    NSString *strSize = [str stringByReplacingOccurrencesOfString:@"G" withString:@""];
//    NSInteger size = strSize.integerValue;
    NSInteger size = (NSInteger)((strSize.floatValue)*MB_UNIT);
    if (size>=_totalSize)
    {
        int totalGB = (int)_totalSize/(MB_UNIT);
        _textNum.text = [NSString stringWithFormat:@"%d",totalGB];
        return NO;
    }
//    else if (size>0&&size<16)
//    {
//        [self showHUDMessage:@"设置空间小于16G,请重新设置"];
//    }
    else
    {
        return YES;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
